package in.wptrafficanalyzer.navigationdrawerdemo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class MainActivity extends Activity {

	// Within which the entire activity is enclosed
	DrawerLayout mDrawerLayout;
	
	// ListView represents Navigation Drawer
	ListView mDrawerList;
	
	// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
	ActionBarDrawerToggle mDrawerToggle;	
	
	// Title of the action bar
	String mTitle="";
	
	private TableLayout user_list;
	private TextView textView_history;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mTitle = (String) getTitle();		
		
		
		// Getting reference to the DrawerLayout
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		
		
		mDrawerList = (ListView) findViewById(R.id.drawer_list);
		
		// Getting reference to the ActionBarDrawerToggle
		mDrawerToggle = new ActionBarDrawerToggle(	this, 
													mDrawerLayout, 
													R.drawable.ic_drawer, 
													R.string.drawer_open,
													R.string.drawer_close){
			
			/** Called when drawer is closed */
            public void onDrawerClosed(View view) {
            	getActionBar().setTitle(mTitle);
            	invalidateOptionsMenu();
                
            }

            /** Called when a drawer is opened */
            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle("Select a river");
                invalidateOptionsMenu();
            }
			
		};
		
		// Setting DrawerToggle on DrawerLayout
		mDrawerLayout.setDrawerListener(mDrawerToggle);
		
		// Creating an ArrayAdapter to add items to the listview mDrawerList
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
					getBaseContext(), 
					R.layout.drawer_list_item  , 
					getResources().getStringArray(R.array.items) 
				);
		
		// Setting the adapter on mDrawerList
		mDrawerList.setAdapter(adapter);
		
		// Enabling Home button
		getActionBar().setHomeButtonEnabled(true);
		
		// Enabling Up navigation
		getActionBar().setDisplayHomeAsUpEnabled(true);
		
		// Setting item click listener for the listview mDrawerList
		mDrawerList.setOnItemClickListener(new OnItemClickListener() {

			
			@Override
			public void onItemClick(AdapterView<?> parent,
							View view,
							int position,
							long id) {			
				
				// Getting an array of rivers
				String[] rivers = getResources().getStringArray(R.array.items);
				
				//Currently selected river
				mTitle = rivers[position];				
				
				
				// Creating a fragment object
				RiverFragment rFragment = new RiverFragment();
				
				// Creating a Bundle object
				Bundle data = new Bundle();
				
				// Setting the index of the currently selected item of mDrawerList
				data.putInt("position", position);
				
				// Setting the position to the fragment
				rFragment.setArguments(data);
				
				// Getting reference to the FragmentManager
				FragmentManager fragmentManager  = getFragmentManager();
				
				// Creating a fragment transaction
				FragmentTransaction ft = fragmentManager.beginTransaction();
				
				// Adding a fragment to the fragment transaction
				ft.replace(R.id.content_frame, rFragment);
				
				// Committing the transaction
				ft.commit();
				
				// Closing the drawer
				mDrawerLayout.closeDrawer(mDrawerList);				
				
				user_list = (TableLayout)findViewById(R.id.tableLayout_notice);
				if (position == 0) {
					user_list.setVisibility(View.VISIBLE);
					getDataFromServer();
				} else
					user_list.setVisibility(View.INVISIBLE);

			}
		});	
		
		
		
		

	}
		
	




	@SuppressLint("NewApi")
	private void getDataFromServer() {
		 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()  
	        .detectDiskReads()  
	        .detectDiskWrites()  
	        .detectNetwork()  
	        .penaltyLog()  
	        .build());  
	        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()  
	        .detectLeakedSqlLiteObjects()   
	        .penaltyLog()  
	        .penaltyDeath()  
	        .build());  
	        
		 
         user_list.setStretchAllColumns(true);
         TableLayout.LayoutParams row_layout = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
         TableRow.LayoutParams view_layout = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
         String event = null;
         try {
         	InputStream is = null;
     		String encodedString = null; // String with php tag code like <link:...>
     		String decodedString = null; // String what we need.
     		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     		//nameValuePairs.add(new BasicNameValuePair("event", "event"));
         	// HTTP Post.
     		try {
     			HttpClient httpClient = new DefaultHttpClient();
     			HttpPost httpPost = new HttpPost("http://143.89.220.85/android_connect_db.php");
     			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     			HttpResponse httpResponse = httpClient.execute(httpPost);
     			HttpEntity httpEntity = httpResponse.getEntity();
     			is = httpEntity.getContent();
     		} catch (Exception e) {
     			Log.e("TAG", "Error in HTTP connection " + e.toString());
     		}
     		
     		// Converting.
     		try {
     			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
     			StringBuilder stringBuilder = new StringBuilder();
     			String line = null;
     			while ((line = bufferedReader.readLine()) != null) {
     				stringBuilder.append(line + "\n");
     			}
     			is.close();
     			// Result.
     			encodedString = stringBuilder.toString();
     		} catch(Exception e) {
     			Log.e("TAG", "Error in converting result " + e.toString());
     		}
             Log.e("A", encodedString);

             JSONArray jsonArray = new JSONArray(encodedString);
             for(int i = 0; i < jsonArray.length(); i++) {
                 JSONObject jsonData = jsonArray.getJSONObject(i);
                 TableRow tr = new TableRow(MainActivity.this);
                 TableRow tr2 = new TableRow(MainActivity.this);
                 tr.setLayoutParams(row_layout);
                 tr.setGravity(Gravity.CENTER_HORIZONTAL);
                 tr2.setLayoutParams(row_layout);
                 tr2.setGravity(Gravity.CENTER_HORIZONTAL);
                 
                 TextView act_event = new TextView(MainActivity.this);
                 //Log.e("B", jsonData.getString("event"));
                 act_event.setText(jsonData.getString("event"));
                 act_event.setLayoutParams(view_layout);
                 
                 TextView starttime = new TextView(MainActivity.this);
                 //Log.e("B", jsonData.getString("starttime"));
                 starttime.setText(jsonData.getString("starttime"));
                 starttime.setLayoutParams(view_layout);
                 
                 tr2.addView(starttime);
                 tr.addView(act_event);
                 user_list.addView(tr2);
                 user_list.addView(tr);
                 
             }
         } catch(Exception e) {
              Log.e("log_tag", e.toString());
         }
	}

	@Override
	 protected void onPostCreate(Bundle savedInstanceState) {
		 super.onPostCreate(savedInstanceState);	     
	     mDrawerToggle.syncState();	
	 }
	
	/** Handling the touch event of app icon */
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {     
        if (mDrawerToggle.onOptionsItemSelected(item)) {
          return true;
        }
        return super.onOptionsItemSelected(item);
    }
	
	
	/** Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	

}
